package com.xianggu.tomcat;

import javax.servlet.ServletInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author chengjy
 * @date 2025/3/6
 */
public class Request extends AbstractHttpServletRequest{
    private String method;
    private String url;
    private String protocol;
    private Socket socket;



    public Request(String method, String url, String protocol, Socket socket) {
        this.method = method;
        this.url = url;
        this.protocol = protocol;
        this.socket = socket;
    }

    public String getUrl() {
        return url;
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public String getMethod() {
        return method;
    }

    @Override
    public StringBuffer getRequestURL() {
        return super.getRequestURL();
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public String toString() {
        return "Request{" +
                "method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", protocol='" + protocol + '\'' +
                '}';
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 从 Socket 中读取数据
        InputStream socketInput = socket.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        // 将 SocketInputStream 的数据读取到缓冲区
        byte[] data = new byte[1024];
        int bytesRead;
        while ((bytesRead = socketInput.read(data)) != -1) {
            buffer.write(data, 0, bytesRead);
        }

        // 将缓冲区的数据封装到自定义的 ServletInputStream
        return new BufferedServletInputStream(buffer.toByteArray());
    }
}
